package com.nuc.bigdata.service.impl;

import com.nuc.bigdata.config.CryptConfig;
import com.nuc.bigdata.exception.BusinessException;
import com.nuc.bigdata.model.ResultCode;
import com.nuc.bigdata.orm.entity.User;
import com.nuc.bigdata.orm.repository.UserRepository;
import com.nuc.bigdata.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.nuc.bigdata.util.CryptUtils;

/**
 * @author JackLuo
 * @date 2019/10/22
 */
@Service
public class LoginServiceImpl implements LoginService {

    private final UserRepository userRepository;

    private final CryptConfig cryptConfig;

    @Autowired
    public LoginServiceImpl(UserRepository userRepository, CryptConfig cryptConfig) {
        this.userRepository = userRepository;
        this.cryptConfig = cryptConfig;
    }

    @Override
    public User login(String loginName, String password) throws Exception {
        User user = userRepository.findUserByLoginName(loginName);
        //查找出的用户为空，登陆返回也是空用户
        if (StringUtils.isEmpty(user)) {
            User backUser = new User();
            backUser.setLoginName(loginName);
            backUser.setPassword(password);
            throw new BusinessException(ResultCode.USER_NOT_EXIST,backUser);
        } else {
            //能查到用户的情况下
                //初始化加密工具
                CryptUtils utils = new CryptUtils(cryptConfig.getKey(), cryptConfig.getAlgorithm());
                //加密用户输入的密码
                String encrypt = utils.encrypt(password);
                //判断用户密码是否和数据库的相等，相等就返回这个用户数据
                if (user.getPassword().equals(encrypt)) {
                    return user;
                }else {
                    User backUser = new User();
                    backUser.setLoginName(loginName);
                    backUser.setPassword(password);
                    throw new BusinessException(ResultCode.USER_PASSWORD_ERROR,backUser );
                }
        }
    }
}
